package cn.schoolwow.util.module.query.instanceList.flow.group;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instance.QueryInstance;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GroupInstanceByFieldBusiness<P,T> implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        List<T> filterInstanceList = (List<T>) flowContext.getData("filterInstanceList");
        String fieldName = (String) flowContext.checkData("fieldName");

        if(null==filterInstanceList){
            return;
        }

        Map<P,List<T>> fieldInstanceListMap = new HashMap<>();
        for(T instance:filterInstanceList){
            P fieldValue = (P) QueryInstance.newQuery(instance).execute().getSingleFieldValue(fieldName);
            if(!fieldInstanceListMap.containsKey(fieldValue)){
                fieldInstanceListMap.put(fieldValue, new ArrayList<T>());
            }
            fieldInstanceListMap.get(fieldValue).add(instance);
        }
        flowContext.putReturnData("fieldInstanceListMap", fieldInstanceListMap);
    }

    @Override
    public String name() {
        return "根据指定字段分组实例列表";
    }
}